#!/bin/sh
# 设定为主数据库
DataDir=/data/mysql
ScriptDir=$(dirname $0)
VIP=192.168.0.222
LogDir=/App/logs
LogFile=$LogDir/drbd.log

test -d $LogDir || mkdir -p $LogDir

while :
do
    drbd_status=$(service drbd status | grep "Inconsistent" | awk '{print $4}')
    if [ -n "$drbd_status" ]; then
        date +'%Y-%m-%d %H:%M:%S' >> $LogFile
        echo "DRBD 数据不一致" >> $LogFile
        sleep 1
    else
        date +'%Y-%m-%d %H:%M:%S' >> $LogFile
        echo "DRBD 状态正常" >> $LogFile
        break
    fi
done

while :
do
    if [ -d "$DataDir" ]; then
        date +'%Y-%m-%d %H:%M:%S' >> $LogFile
        $ScriptDir/mysql start
        echo "启动数据库($?)" >> $LogFile
        break
    else
        date +'%Y-%m-%d %H:%M:%S' >> $LogFile
        $ScriptDir/drbd master >> $LogFile 2&>1
        echo "切换为主DRBD($?)" >> $LogFile
        sleep 1
        $ScriptDir/mysql start
        echo "启动数据库($?)" >> $LogFile
        break
    fi    
done

drbd_status=$(service drbd status | grep "StandAlone" | awk '{print $2}')
if [ -n "$drbd_status" ]; then
    vip_status=$(ip addr | grep eth0 | grep "$VIP")
    if [ -n "$vip_status" ]; then
        for i in $(seq 3)
        do
            drbdadm connect all
            sleep 2
        done
    fi
fi
